# -*- coding: utf-8 -*-


import os
import random
from io import BytesIO

from PIL import Image, ImageDraw, ImageFilter, ImageFont

from apps import configs
from apps.log import Logger
from apps.utils import Utils


class ValidCodeImg(object):

    
    def __init__(self, width=200, height=70, code_count=6, font_size=65):
        self.width = width
        self.height = height
        self.code_count = code_count
        self.font_size = font_size

    def getRandomColor(self):
        c1 = random.randint(0, 255)
        c2 = random.randint(0, 255)
        c3 = random.randint(0, 255)
        return (c1, c2, c3)

    def getValidCodeImg(self):
        image = Image.new('RGB', (self.width, self.height), (255, 255, 255))

        draw = ImageDraw.Draw(image)
        font = ImageFont.truetype(os.path.join(configs.BASE_DIR, 'font',
                                               'Monaco.ttf'),
                                  size=self.font_size)
        code = Utils.get_checkcode(self.code_count, False)
        for i, v in enumerate(code):
            draw.text((10 + i * 30, 0), v, self.getRandomColor(), font=font)

        # 噪点噪线
        # 划线
        for i in range(20):
            x1 = random.randint(0, self.width)
            x2 = random.randint(0, self.width)
            y1 = random.randint(0, self.height)
            y2 = random.randint(0, self.height)
            draw.line((x1, y1, x2, y2), fill=self.getRandomColor())

        with BytesIO() as f:
            image = image.filter(ImageFilter.EDGE_ENHANCE)
            image = image.filter(ImageFilter.SMOOTH_MORE)
            # image = image.filter(ImageFilter.BLUR)
            # image = image.convert('L')
            image.save(f, format='PNG')
            data = f.getvalue()

        return data, code
